package com.changshengwei;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * @author 07509-Chang Shengwei
 * @version Id: LambdaUsage.java, v 0.1 2021/6/3 16:22 Chang Shengwei Exp $
 * @description
 */
public class LambdaUsage {

    /**
     * predicate使用
     * @param source
     * @param predicate
     * @return
     */
    private static List<Apple> testPredicate(List<Apple> source, Predicate<Apple> predicate){
        List<Apple> resultList = new ArrayList<>();
        for(Apple apple : source){
            if (predicate.test(apple)){
                resultList.add(apple);
            }
        }

        return resultList;
    }


    private static void testSupply(Supplier<Object> s){
        System.out.println(s.get().getClass());
    }

    private static void testConsumer(List<Apple> apples, Consumer<Apple> consumer){
        for (Apple apple : apples){
            consumer.accept(apple);
        }
    }

    private static String testFunction(Object fruit, Function<Object, String> f){
        return f.apply(fruit);
    }

    private static Apple testSupply2(Supplier<Apple> supplier){
        return supplier.get();
    }

    public static void main(String[] args) {
        List<Apple> apples = Arrays.asList(new Apple("green", 120), new Apple("yellow", 130),
                new Apple("red", 150));

        // predicate
        List<Apple> greenApples = testPredicate(apples, x -> "green".equals(x.getColor()));

        // supply 函数推导
        testSupply(String::new);
        Apple apple = testSupply2(() -> new Apple("green", 150));

        // consumer
        testConsumer(apples, a -> System.out.println(a));

        // function
        String appleString = testFunction(new Apple("red", 150), x -> x.toString());
        String orangeString = testFunction(new Orange("red", 150), x -> x.toString());
        System.out.println(appleString);
        System.out.println(orangeString);

    }
}
